<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chat with AI</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<div id="chat-box"></div>
<input type="text" id="user-input">
<button onclick="sendMessage()">Send</button>

<script>
    let messages = [];  // 用于存对话记录

    function sendMessage() {
        let question = $('#user-input').val();
        if (question === "1") {
            // 输出对话记录
            for (let i = 0; i < messages.length; i++) {
                let role = messages[i]['role'];
                let content = messages[i]['content'];
                $('#chat-box').append(`${datadist[role]}: ${content}<br>`);
            }
            return;
        }

        messages.push({'role': 'user', 'content': question});

        $.ajax({
            url: 'https://api.chatanywhere.com.cn/v1',
            type: 'POST',
            headers: {
                'Authorization': 'Bearer sk-QGP7ircB5lgIszv3vlq2ySuYXUg9XfImqSBhr5PDulnY3Azs'
            },
            data: JSON.stringify({
                model: 'gpt-3.5-turbo',
                messages: messages,
                stream: true
            }),
            contentType: 'application/json',
            success: function(response) {
                let coding = {'role': 'assistant', 'content': ''};
                response.messages.forEach(function(event) {
                    try {
                        let text = event.choices[0].delta.content;
                        console.log(text);
                        $('#chat-box').append(text);
                        coding.content += text;
                    } catch (err) {
                        console.error(err);
                    }
                });
                messages.push(coding);
            },
            error: function(xhr, status, error) {
                console.error(error);
            }
        });
    }
</script>
</body>
</html>
